package com.zhan.xioj.aop;

import com.zhan.xioj.annotation.AuthCheck;
import com.zhan.xioj.exception.BusinessException;
import com.zhan.xioj.exception.ErrorCode;
import com.zhan.xioj.model.entity.User;
import com.zhan.xioj.model.enums.UserRoleEnum;
import com.zhan.xioj.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class AuthInterceptor {
    @Resource
    private UserService userService;


    /**
     * 使用环绕切点，执行拦截，对有@AuthCheck注解的方法进行拦截
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     */
    @Around("@annotation(authCheck))")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //获取当前方法的角色
        String mustRole = authCheck.mustRole();
        //RequestContextHolder是一个请求上下文对象，可以获取到当前请求的所有属性
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        //把requestAttributes转成子实现类，可以使用子实现类的getRequest()获取到request对象
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //不需要权限，放行
        if (mustRoleEnum == null) {
            joinPoint.proceed();
        }
        //必须有权限,才能通过，判断当前登录用户是否有权限
        //获取用户权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        if (userRoleEnum == null)  {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 如果被封号，直接拒绝
        if (UserRoleEnum.BAN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //如果权限需要管理员，但是当前用户不是管理员，抛异常
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //通过权限检验，放行
        return joinPoint.proceed();
    }
}
